package security;

import models.User;
import play.Application;

import com.feth.play.module.pa.service.UserServicePlugin;
import com.feth.play.module.pa.user.AuthUser;
import com.feth.play.module.pa.user.AuthUserIdentity;

public class ConsoleUserServicePlugin extends UserServicePlugin {
	
	public ConsoleUserServicePlugin(Application app) {
		super(app);
	}
	
	@Override
	public Object save(AuthUser authUser) {
		final boolean userExists = User.existsByAuthUserIdentity(authUser);
		String userId = null;
		if (!userExists) {
			userId = User.create(authUser).getIdentifier();
		}
		return userId;
	}
	
	@Override
	public AuthUser merge(AuthUser newUser, AuthUser oldUser) {
		if (!oldUser.equals(newUser)) {
			User.merge(oldUser, newUser);
		}
		return oldUser;
	}
	
	@Override
	public AuthUser link(AuthUser oldUser, AuthUser newUser) {
		User.addAccount(oldUser, newUser);
		return newUser;
	}
	
	@Override
	public AuthUser update(final AuthUser authUser) {
		User.setLastLoginDate(authUser);
		return authUser;
	}
	
	@Override
	public Object getLocalIdentity(AuthUserIdentity identity) {
		final User user = User.findByAuthUserIdentity(identity);
		return user != null ? user.getIdentifier() : null;
	}
	
}
